package com.ms.p2p.controller.admin;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.mapper.JsonMapper;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.controller.BaseController;
import com.ms.p2p.entity.system.AdminUser;
import com.ms.p2p.entity.system.RbacDept;
import com.ms.p2p.entity.system.RbacRole;
import com.ms.p2p.entity.system.Setting;
import com.ms.p2p.provider.AdminUserProvider;
import com.ms.p2p.provider.RbacProvider;
import com.ms.p2p.provider.SettingProvider;
import com.ms.p2p.utils.JsonDataGridHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller("AdminSystemController")
@RequestMapping({ "/admin/rbac" })
public class AdminSystemController extends AdminBaseController {


	@Reference
	private SettingProvider settingProvider;


	@Reference
	private AdminUserProvider adminUserProvider;

	@Reference
	private RbacProvider rbacProvider;

	@RequestMapping("index")
	public String rbac() {
		return "admin/system/rbac";
	}


	/**
	 * 获取部门数据
	 * @param request
	 * @param session
	 * @param page
	 * @return
	 */
	@RequestMapping(value = {"/queryData"}, produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public PageBean queryData(HttpServletRequest request, HttpSession session,
							  PageBean page
	) {
		page.setList(rbacProvider.getPager(page));
		page.setTotalCount(rbacProvider.findCount());
		return JsonDataGridHelper.createJSONData(page);
	}

	/**
	 * 获取人员数据
	 * @param request
	 * @param session
	 * @param page
	 * @return
	 */
	@RequestMapping(value = {"/queryEmpData"}, produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public PageBean queryEmpData(HttpServletRequest request, HttpSession session
			, @RequestParam(value = "empId",required = false) String empId
			, @RequestParam(value = "userName",required = false) String userName
							  ,PageBean page
	) {
		page.setList(adminUserProvider.findPager(userName,empId,page));
		page.setTotalCount(adminUserProvider.findCount(userName,empId));
		return JsonDataGridHelper.createJSONData(page);
	}

	@RequestMapping("/global")
	public String toParameterSettings(HttpServletRequest request) {
		String type = request.getParameter("type");
		if(type == null || ("".equals(type))){
			type = "1";
		}
		List<Setting> parameters = settingProvider.findAll();
		request.setAttribute("parameters", parameters);
		request.setAttribute("type", type);
		return "admin/system/setting";
	}

	@RequestMapping("/saveSettings")
	@ResponseBody
	public Message parameterSettings(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException, IntrospectionException{

			List<Setting> parameters = settingProvider.findAll();
			for (Setting systemParam : parameters) {
				systemParam.setText(request.getParameter(systemParam.getCode()));
				settingProvider.update(systemParam);
			}

		return	Message.success("修改成功");
	}

	@RequestMapping("/deleteSettings/{id}")
	public String deleteSettings(@PathVariable String id,HttpServletRequest request, RedirectAttributes redirectAttributes) throws IllegalAccessException, InvocationTargetException, IntrospectionException{
		settingProvider.delete(id);
		addFlashMessage(redirectAttributes, Message.success("删除成功"));
		return	"redirect:/admin/rbac/global.aspx";
	}


	@RequestMapping(value = { "/getRoles" })
	@ResponseBody
	public Map<String, Object> getRole(HttpServletRequest request, HttpSession session,
									   HttpServletResponse res) throws IOException {

			String deptid = request.getParameter("deptid");
			List <Map<String,Object>> list = rbacProvider.getRoles(deptid);
			Map<String,Object> map = new HashMap();
			map.put("list",list);
			return map;

	}


	@RequestMapping(value = { "/getDepts" })
	public void getDepts(HttpServletRequest request, HttpSession session,
						 HttpServletResponse res) throws IOException {
		AdminUser user = getCurrentEmp();
		List list = rbacProvider.findDepts();
		Map map = new HashMap();
		map.put("deptlist", list);
		String json = JsonMapper.toJsonString(map);
		res.setContentType("text/html;charset=UTF-8");
		res.getWriter().print(json);



	}

	@RequestMapping(value = { "/delemp" })
	public void delemp(HttpServletRequest request, HttpSession session,
					   HttpServletResponse res) throws IOException {
		AdminUser user = getCurrentEmp();
		String id = request.getParameter("id");
		res.setContentType("text/html;charset=UTF-8");
		adminUserProvider.delete(Integer.parseInt(id));
		res.getWriter().print("删除成功");
	}


	@RequestMapping(value = { "/saveRoles" })
	public void saveRoles(HttpServletRequest request, HttpSession session,
						  HttpServletResponse res) throws Exception {
		AdminUser user = getCurrentEmp();
		Map map = new HashMap();
			String roles = request.getParameter("roles");
			String deptid = request.getParameter("deptid");
			// 获取权限们

			if(roles.length()>1){
				roles = roles.substring(0, roles.length() - 1);
			}
			String[] role = roles.split(",");
			res.setContentType("text/html;charset=UTF-8");
			rbacProvider.deleteByDeptAndRoles(deptid,role);
			map.put("state", "成功");
			res.getWriter().print(JsonMapper.toJsonString(map));


	}



	@RequestMapping({ "/findchild" })
	public String findchild(HttpServletRequest request, HttpSession session) {
		String pid = request.getParameter("id");
		AdminUser user = getCurrentEmp();
			int dept_id = user.getDepart();
			List<RbacRole> list1 = rbacProvider.findDeptRolesByPid(dept_id,pid);
			for (int i = 0; i < list1.size(); i++) {
				RbacRole role = list1.get(i);
				ArrayList<RbacRole> list2 = (ArrayList<RbacRole>) rbacProvider
						.findDeptRolesByPid(dept_id, role.getId() + "");
				list1.get(i).setChildrole(list2);
			}
			request.setAttribute("list", list1);

		return "admin/common/admin_menu";

	}

	@RequestMapping({ "/queryDept" })
	public String queryDept(HttpServletRequest request, HttpSession session) {
		AdminUser emp = getCurrentEmp();
		if (emp != null) {
			PageBean page = new PageBean();
			String currentPage = request.getParameter("currentPage");
			if (currentPage != null && !(("").equals(currentPage))) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}
			page.setTotalCount(rbacProvider.findCount());
			List<HashMap<String,Object>>list = rbacProvider.findPager(page);
			request.setAttribute("list", list);
			request.setAttribute("page", page);
		}

		return "admin/dept/list";

	}

	@RequestMapping({ "/editDept" })
	public String editDept(HttpServletRequest request, HttpSession session,
						   HttpServletResponse res) {
		AdminUser user = getCurrentEmp();
		res.setContentType("text/html;charset=UTF-8");
		if (user != null) {

			String id = request.getParameter("id");
			RbacDept dept = null;
			if (id != null && !"".equals(id)) {
				dept = rbacProvider.selectDeptByid(id);

			}
			request.setAttribute("dept", dept);

		}
		return "admin/dept/add";

	}

	@RequestMapping({ "/deptCg" })
	@ResponseBody
	public Message deptCg(HttpServletRequest request, HttpSession session,
						 HttpServletResponse res) throws Exception {
		AdminUser user = getCurrentEmp();
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		rbacProvider.saveOrupdate(id, name);


		return Message.success("操作成功！");
	}

	@RequestMapping({ "/queryEmp" })
	public String queryEmp(HttpServletRequest request, HttpSession session, @RequestParam(value = "userId",required = false) String empId,
						   @RequestParam(value = "userName",required = false) String userName

	) {
		AdminUser emp = getCurrentEmp();
		if (emp != null) {
			String whereStr = " where 1=1  ";
			PageBean page = new PageBean();
			page.setPageSize(10);
			String currentPage = request.getParameter("currentPage");
			if (currentPage != null && !(("").equals(currentPage))) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}

			page.setTotalCount(adminUserProvider.findCount(userName,empId));
			List<AdminUser> list = adminUserProvider.findPager(userName,empId,page);
			request.setAttribute("list", list);

			request.setAttribute("page", page);

			// 搜索条件
			request.setAttribute("userId", empId);
			request.setAttribute("userName", userName);

		}

		return "admin/user/list";

	}

	@RequestMapping({ "/editEmp" })
	public String editEmp(HttpServletRequest request, HttpSession session) {
		AdminUser user = getCurrentEmp();
		if (user != null) {
			String emp_id = request.getParameter("id");
			List deptlist = rbacProvider.findDepts();
			AdminUser emp = null;
			request.setAttribute("deptlist", deptlist);
			if (emp_id != null && !"".equals(emp_id)) {
				emp = adminUserProvider.findById(emp_id);

			} else {
				return "admin/user/edit";
			}
			request.setAttribute("emp", emp);

		}

		return "admin/user/edit";
	}

	@RequestMapping({ "/empCg" })
	@ResponseBody
	public Message empCg(HttpServletRequest request, HttpSession session,
						HttpServletResponse res) throws IOException {
		AdminUser user = getCurrentEmp();
		if (user != null) {
			String user_id = request.getParameter("userid");
			String dept_id = request.getParameter("dept_id");
			String password = request.getParameter("password");
			String name = request.getParameter("username");
			String admin_name = request.getParameter("admin_name");
			int i = adminUserProvider.updateEmp(user_id, dept_id, password, name, admin_name);
		}
		return Message.success("操作成功！");
	}

	@Override
	public boolean getBinderFlag() {
		return true;
	}
}
